package com.guardchina.framework.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 描述：选择引入的service配置
 * @author lwb
 * @date 2019/3/14 16:21
 */
@Slf4j
public class WebConfigurationSelector implements ImportSelector {

    private static final String CONFIGURATIONS_ATTRIBUTE_NAME = "plugins";

    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {

        Map<String, Object> mapAttributes = importingClassMetadata.getAnnotationAttributes(EnableWebPlugins.class.getName(), false);

        AnnotationAttributes attributes = Optional.ofNullable(mapAttributes).map(AnnotationAttributes::new).orElse(null);

        List<String> imports = new ArrayList<>();

        imports.add(WebMvcConfiguration.class.getName());

        if(attributes == null){
            log.info("No web plugin configuration find");
        }else{
            Class<?>[] configurations = attributes.getClassArray(CONFIGURATIONS_ATTRIBUTE_NAME);
            for (Class<?> configuration : configurations) {
                imports.add(configuration.getName());
            }
        }


        return imports.toArray(new String[0]);
    }
}
